﻿//for load list as grid by post data
(function ($) {
    $.fn.loadGrid = function (settings) {
        var holder = $(this);
        var defaults = {
            url: "",
            data: "",
            pageNo: "1",
            makeHover: true,
            callback: "",
            isBlockUI: false,
            assignTableClass: true,
            isMakePaging :true,
            isAutoHeight:false,
            //openPageSize:false,
        }
        var exception ="";
        if($(holder).size() == 0)
        {
            exception="$.loadGrid : without holder";
        }
        if(exception == "")
        {
            var options = jQuery.extend(defaults, settings);
            //options.isBlockUI= false
            loadGridView(holder, options);
        }else{
            alert(exception);
        }
        
        

        function loadGridView(holder, options) {
            //$(holder).height('auto');
            if (options.isBlockUI == true) {
                $.blockUI({
                //$(holder).block({ //block
                    theme: false, // true to enable jQuery UI support
                    //title: "Loading ...", // only used when theme == true
                    message: "<img src=\"/content/Images/loading.gif\">",
                    //timeout: 5000,
                    css:  $('body').data('webConfig').loaddingCss,
                    overlayCSS: { backgroundColor: '#000', opacity: 0.5, cursor: 'wait' },
                    //onUnblock: loadGridView(holder, options)
                }); //end block del
            }
            $(holder).html('<div class="openPage" style="width:' + $(holder).width() + 'px;height:' + $(holder).height() + 'px"></div>');
            if($(holder).prev(".attrGrid:first").size() == 0){
                $(holder).before('<div class="attrGrid" style="display:none" pageSize="30"></div>');
            }
            //if (options.data) {
            //alert(($("body").data("pageSize") == "") ? 0 : $("body").data("pageSize"));
            var pagesize = 0;
            try{
                pagesize= $(holder).prev(".attrGrid:first").attr("pageSize");
            }catch(e){}
            var dataPaging = { "pageNo": options.pageNo,"PageSize":pagesize };
            var ajaxTime = { "ajaxTime": new Date().getTime() };
            var dataSend = jQuery.extend(dataPaging, options.data)
            dataSend = jQuery.extend(ajaxTime, dataSend)
            $.post(options.url, dataSend, function (data) {
                $(holder).html(data).show(5, function () {
                    if(options.isMakePaging == false){
                        CreateGrid(holder, options,data);
                        //window.setTimeout("document.body.style.cursor = 'auto';", 500);
                        //$(holder).parent().unblock().fadeIn(); //unblock and block
                        //$.unblockUI();
                    }else{
                        //check if rows empty && totalitem > 0 : trick maxpage
                        if($(holder).find("table:first").find("tbody tr").size() == 0 && $(holder).find("table:first").attr("totalitem") > 0){
                            $.unblockUI();
                            options.pageNo = options.pageNo -1; 
                            $(holder).loadGridView(options);
                        }else{
                            CreateGrid(holder, options,data);
                            //window.setTimeout("document.body.style.cursor = 'auto';", 500);
                            //$(holder).parent().unblock().fadeIn(); //unblock and block
                        }
                    }
                });
                
            });

            //            } else {
            //                alert(options.url);
            //                $(holder).load(options.url, function() {
            //                    alert("xxx");
            //                    $(this).show(5, function() {
            //                        //calback
            //                        if (options.callback) { eval(options.callback) };
            //                    });
            //                });
            //            }
        }
        function CreateGrid(holder, options,data) {
            var selector = $(holder).find("table.jq-tableGrid");
            if (options.assignTableClass == true) {
                AssignTableClass(selector, options);
                AssignCutText(holder); //ตัดคำให้พอดีคอลัมน์แล้วเติม... แต่ต้องกำหนด width ให้ คอลัมน์นั้นด้วย
            }
            if(options.isMakePaging == true){
                makePaging(holder, selector, options);
            }
            FreezeHeaer(holder);
            makeOrderBy(holder,selector,options);
            AutoHeightGrid(holder,selector,options);
            if (options.callback) { 
                var n = options.callback.indexOf("()");
                if(n > 0){
                    eval(options.callback);
                }else{
                    eval(options.callback) (holder);
                }
            };
            //$(holder).unblock();
            $.unblockUI();
        }
        //--------------------------------------function for make paging
        function makePaging(holder, selector, options) {
            $(selector).twTablePager({//assign twTablePage plug-in to selector
                currentPage: $(selector).attr("currentpage"), //get currentPage from selector attribute
                maxPage: $(selector).attr("maxpage"), //get maxPage from selector attribute
                totalItems: $(selector).attr("totalitem"),
                pageSize: $(selector).parents("div").prev(".attrGrid:first").attr("pageSize"),
                onPaging: function (pageNumber) {
                    options.pageNo = pageNumber;
                    $(holder).loadGrid(options); //set onPaging function to loadlist with pageNumber option
                }
            });
        }
        function AutoHeightGrid(holder, selector, options) 
        {
            if(options.isAutoHeight){
                var height = $(selector).height() + 10;
                $(holder).find(".divOFGridList").height(height);
            }
        }

        //--------------------------------------function for make order by
        function makeOrderBy(holder, tableGrid, options)
        {
            $(holder).find(".fixHeader table thead").find("th").each(function(){
                if ($(this).attr("sortby") != undefined && $(this).attr("sortby") != "")
                {
                    //insert orderby control
                    $(this).append('<div style="position:absolute;top:0px;height:120px;cursor:pointer" class="btn-OrderBy">^</div>');
                    $(this).append(contentsControl);

                    var caption = $(this).attr("captionSortBy");
                    var sortby = $(this).attr("sortby");
                    var captionList = caption.split(",");
                    var sortbyList = sortby.split(",");
                    var op ="";
                    for(var i = 0;i< captionList.length;i++)
                    {
                        op+='<option style="null" value="'+sortbyList[i]+'" value1="null" value2="null" value3="null">'+captionList[i]+'</option>';
                    }
                    var html = '<select class="select-sortby">'+op+'</select>';
                    var contentsControl = '<div style="display:none;position:absolute;z-index:1999; height:100px;top:0px;background-color: rgb(238, 238, 240);" class="contentsControl">'
                    +'<div style="margin:10px;">'+html+'</div>'
                    +'<div style="margin:10px;"><select class="select-orderby">'
                        + '<option style="null" value="ASC" value1="null" value2="null" value3="null">ASC</option>'
                        + '<option style="null" value="DESC" value1="null" value2="null" value3="null">DESC</option>'
                    +'</select></div>'
                    +'<div><span style="margin:5px;cursor:pointer" class="btn-sorting">sorting</span></div>'
                    +'</div>';
                    $(this).append(contentsControl);
                    $(this).addClass("orderByControl");
                }
            });
                $(holder).find(".fixHeader table thead").find(".btn-OrderBy").click(function () {
                      $(this).parents("th").find(".contentsControl").show();
//                      $(this).parents("th").find(".contentsControl").mouseleave(function ()
//                      {
//                            $(this).parents("th").find(".contentsControl").hide();
//                      });
                });
                $(holder).find(".fixHeader table thead").find(".btn-sorting").click(function () {
                      var thHolder = $(this).parents("th");
                      //set order by into attr(orderby)
                      $(thHolder).attr("orderby",$(thHolder).find(".select-sortby").val() + " " + $(thHolder).find(".select-orderby").val());
                      $(this).parents("th").find(".contentsControl").hide();
                      //get data from order by
                      var dataSend = "";
                      var i=0;
                      $(holder).find(".fixHeader table thead").find("th").each(function(){
                          if($(this).attr("orderby") != undefined && $(this).attr("orderby") != "" ){
                                if(dataSend == ""){
                                    dataSend+=$(this).attr("orderby");
                                }else{
                                    dataSend+="," + $(this).attr("orderby");
                                }
                          }
                          i++;
                      });
                      var orderByOption = {"orderByOption":dataSend};
                      options.data = jQuery.extend( options.data,orderByOption);
                      //alert(options.data.orderByOption);
                      $(holder).loadGrid(options);
                });
        }

        function AssignCutText(holder) {
            $(holder).find('.cutword').each(function () {
                $(this).html('<div class="doCutText" title="' + $.trim($(this).text()) + '" style="overflow: hidden;text-overflow: ellipsis;-o-text-overflow: ellipsis;white-space: nowrap;width:' + $(this).width() + 'px">' + $.trim($(this).text()) + '</div>');
            });
        }

        function FreezeHeaer(holder) {
            var gridID = $(holder).attr("id");
            holder=$(holder).find(".divOFGridList");
            $(holder).find("div.fixHeader").html("");
            $(holder).find(".fixHeader").css({ "position": "absolute", "z-index": "500" });
            var header = $(holder).find("table.jq-tableGrid").clone(false, false);
            $(header).removeClass("jq-tableGrid");
            $(header).find("tbody").find("tr").each(function(){
                $(this).remove();
            });
            makeCheckBoxAll(header,$(holder).find("table.jq-tableGrid"),gridID);
            $(holder).find(".fixHeader").html(header);
            $(holder).scroll(function () {
                var st = $(this).scrollTop();
                if (st > 0) {

                } else {

                }
                $(this).find(".fixHeader").css("top",st);
            });
        }

        function makeCheckBoxAll(header,base,gridID)
        {
            var count = 0;
            var isChecked = 'false';
            $(header).find("tr").find("th").each(function(){
                if($(this).attr("classCheckboxAll") !='undefined' && $(this).attr("classCheckboxAll") != null){
                    if($(this).attr("isChecked") !='undefined')
                    {
                        isChecked = $(this).attr("isChecked");
                    }
                    var clssGroup = $(this).attr("classCheckboxAll");
                    $(this).append('<div><span isChecked="'+isChecked+'" classGroup="'+clssGroup+'"  class="checkBoxHeader '+$(this).attr("classCheckboxAll")+'" style="display:inline-block;margin-top:5px;width:13px;height:13px;" ><span></div>');
                    count = count +1;
                    //event of child checkbox
                    $(base).find("tbody").find("."+clssGroup).click(function(){
                        var checkedNum=$(base).find("tbody").find("."+clssGroup+":checked").size();
                        var uncheckedNum=$(base).find("tbody").find("."+clssGroup).size();
                        if(checkedNum == uncheckedNum){
                            var point = $("#"+gridID).find(".fixHeader").find("thead").find("."+clssGroup);
                            $(point).removeClass("ui-checkbox-unchecked");
                            $(point).addClass("ui-checkbox-checked");
                        }else{
                            var point = $("#"+gridID).find(".fixHeader").find("thead").find("."+clssGroup);
                            $(point).removeClass("ui-checkbox-checked");
                            $(point).addClass("ui-checkbox-unchecked");
                        }
                        
                    });
                    //--end event of child checkbox
                    if(isChecked == 'true')
                    {
                        $(this).find(".checkBoxHeader").addClass("ui-checkbox-checked");
                    }else{
                        $(this).find(".checkBoxHeader").addClass("ui-checkbox-unchecked");
                    }
                    $(this).find(".checkBoxHeader").click(function(){
                        //ตรวจสอบว่าปัจุจบันคืออะไร
                        if($(this).hasClass("ui-checkbox-unchecked"))
                        {
                            $(this).attr("isChecked",false);
                        }
                        //loop checked all
                        if($(this).attr("isChecked") == 'false'){
                            $(base).find("tbody").find("input."+$(this).attr("classGroup")).each(function(){
                                $(this).attr("checked","checked");
                            });
                            $(this).attr("isChecked",true);
                            $(this).removeClass("ui-checkbox-unchecked");
                            $(this).addClass("ui-checkbox-checked");
                            
                        }else{
                             $(base).find("tbody").find("input."+$(this).attr("classGroup")).each(function(){
                                $(this).removeAttr("checked");
                            });
                            $(this).attr("isChecked",false);
                            $(this).removeClass("ui-checkbox-checked");
                            $(this).addClass("ui-checkbox-unchecked");
                        }
                    });
                }
            });
            if(count > 0)
            {
                var trHeight="";
                if($(header).find("tr:first").height()==0){
                    $(base).find("tr").height("54");
                    $(header).find("tr:first").height("54");
                }else{
                    $(base).find("tr").css("height",$(header).find("tr:first").height());
                }
            }
        }
        
        
        //assign class to <table>
        function AssignTableClass(holder, options, emptyCaption) {
            //clear Alpha
            $(holder).find("td").each(function(){
                if($(this).parents("table").hasClass("subTable") == false){
                    var valign = $(this).css('vertical-align');
                    //$(this).removeAttr('style');
                    $(this).css('vertical-align',valign);
                }
            })
            
            
            //empty row
            if (!$(holder).find("tbody tr").size()) {
                if (!emptyCaption) { emptyCaption = "Empty Data" }
                //find colspan size
                var colspansize = 0;
                var thisColspan = 30;
                //var thisColspan = Number($(holder).find("thead tr:first th").size() + colspansize);
                $(holder).find("tbody").append('<tr class="emptyRow"><td align="center" style="height:50px" colspan="' + thisColspan + '">' + emptyCaption + '</td></tr>')
            }
            //add class
            if ($(holder).is("table")) {//Direct assign to table 
                $(holder).attr({ cellspacing: 0, cellpadding: 4 }).addClass("tw-ui-makeList ui-widget ui-widget-content")
		            .css({ 'white-space': 'nowrap' })
		            .find("th").addClass("ui-widget-header")
		            .end().find("td").each(function(){
                        if($(this).parents("table").hasClass("subTable") == false){
                            $(this).addClass("ui-widget-content");
                        }
                    })
            } else { //assign to holder
                $(holder).find("table").attr({ cellspacing: 0, cellpadding: 4 }).addClass("tw-ui-makeList ui-widget ui-widget-content")
		            .css({ 'white-space': 'nowrap' })
		            .find("th").addClass("ui-widget-header")
		            .end().find("td").addClass("ui-widget-content");
            }
            //.end().find("tr:even td").css({ opacity: .90, filter: 'Alpha(Opacity=90)' });

            //hover
            if (options.makeHover) {
                $(holder).find("tbody tr").hover(
		          function () {
		              $(this).find("td").addClass("ui-state-focus");
		          }, function () {
		              $(this).find("td").removeClass("ui-state-focus");
		          }
                );
            }
        };



    };
})(jQuery);
